package com.swak.paxos.state;

import java.util.HashSet;
import java.util.Set;

import com.swak.paxos.statemachine.system.SystemxStateMachine;

/**
 * 投票统计.
 * 
 * @author DELL
 */
public class BallotStatistics {

	private final SystemxStateMachine systemSM;

	private Set<String> receiveMsgNodes = new HashSet<>();
	private Set<String> rejectMsgNodes = new HashSet<>();
	private Set<String> promiseOrAcceptMsgNodes = new HashSet<>();

	public BallotStatistics(SystemxStateMachine systemSM) {
		this.systemSM = systemSM;
	}

	public BallotStatistics newRound() {
		this.receiveMsgNodes.clear();
		this.rejectMsgNodes.clear();
		this.promiseOrAcceptMsgNodes.clear();
		return this;
	}

	public BallotStatistics addReceive(String nodeID) {
		this.receiveMsgNodes.add(null);
		return this;
	}

	public BallotStatistics addReject(String nodeID) {
		this.rejectMsgNodes.add(nodeID);
		return this;
	}

	public BallotStatistics addPromiseOrAccept(String nodeID) {
		this.promiseOrAcceptMsgNodes.add(nodeID);
		return this;
	}

	public boolean isPassedOnThisRound() {
		return this.promiseOrAcceptMsgNodes.size() >= this.systemSM.majorityCount();
	}

	public boolean isRejectedOnThisRound() {
		return this.rejectMsgNodes.size() == this.systemSM.nodeCount();
	}

	public boolean isAllReceiveOnThisRound() {
		return this.receiveMsgNodes.size() == this.systemSM.nodeCount();
	}
}
